package leetcode.code1439;

import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int kthSmallest(int[][] mat, int k) {
		int m = mat.length, n = mat[0].length;
		PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[m] - b[m]);// 和，列
		int ans = 0;
		int[] arr = new int[m + 1];
		for (int i = 0; i < m; i++) {
			ans += mat[i][0];
			arr[i] = 1;
		}
		arr[m] = ans;
		int hash = hash(arr);
		queue.add(arr);
		Set<Integer> add = new HashSet<>();
		add.add(hash);
		while (k > 0) {
			int[] cur = queue.poll();
//			System.out.println(cur[m]);
//			H.print(cur);
			if (--k == 0) {
				return cur[m];
			}
			for (int i = 0; i < m; i++) {
				if (cur[i] < n) {
					arr = cur.clone();
					arr[m] = cur[m] - mat[i][cur[i] - 1] + mat[i][cur[i]];
					arr[i] = cur[i] + 1;
					if (add.add(hash(arr))) {
						queue.add(arr);
					}
				}
			}
		}
		return -1;
	}

	int mod = (int) 1e9 + 7;

	private int hash(int[] arr) {
		long ans = 0;
		for (int i = 0; i < arr.length - 1; i++) {
			ans *= 42;
			ans += arr[i];
			ans %= mod;
		}
		return (int) ans;
	}

	@Override
	public void debug4() {
		H.compare(9, this.kthSmallest(H.str2array1("[[1,10,10],[1,4,5],[2,3,6]]"), 7));
		H.compare(7, this.kthSmallest(H.str2array1("[[1,3,11],[2,4,6]]"), 5));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
